<template>
  <div class="upload">
      <nav-bar />
      <div class="upload-div">
        <div ref="cans" id="upDiv"></div>
        <p class="tip">待上传的文件(原图和缩略图)： {{queryArr.length}}双</p>
        <el-select
          v-model="dirName"
          clearable
          filterable
          allow-create
          default-first-option
          placeholder="请选择上传文件夹">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <div class="btn-area"
          v-loading="loading"
          element-loading-background="rgba(255, 255, 255, 0.6)"
        >
          <el-button type="warning" round class="upload-area">
            选择文件
            <input id="file" type="file" @change="showFiles()" multiple />
          </el-button>
          <el-button type="success" round @click="dealPic()">开始上传</el-button>
        </div>
        <div v-if="loading" class="progress-area">
          <el-progress type="circle" :percentage="percentage" :color="colors"></el-progress>
          <span>上传进度</span>
        </div>
      </div>
  </div>
</template>

<script>
import NavBar from '../components/NavBar.vue';
import { git } from '../config/info'
export default {
    name: 'upload',
  components: {
    NavBar
  },
    data() {
    return {
      data: git,
      fileList: [],
      picThList: [],
      picList: [],
      tokenStr: '',
      dirName: "杂",

      queryArr: [],
      loading: false,
      percentage: 0,
      colors: [
        {color: '#D53E4F', percentage: 20},
        {color: '#FDAE61', percentage: 40},
        {color: '#3288BD', percentage: 60},
        {color: '#E6F598', percentage: 80},
        {color: '#5CB87A', percentage: 100}
      ],
      options: [{
          value: '杂',
          label: '杂'
        }, {
          value: '风景',
          label: '风景'
        }, {
          value: '二次元',
          label: '二次元'
        }],
    };
  },
  methods: {
      async showFiles() {
        let myFile = document.getElementById('file')
        if(myFile.files.length==0){
            return []
        }
        let tmp = new Array(...myFile.files)
        for(let i=0; i<this.fileList.length; ++i) {
            let tmp1 = tmp.filter(e => {
                return e.name != this.fileList[i].name
            })
            tmp = tmp1
        }
        this.fileList = [...this.fileList, ...tmp]
        await this.getQueryArr(tmp)
        console.log(this.queryArr);
        console.log(myFile.files, this.fileList);
        return tmp
    },
    async upload(data) {
        console.log(data);
        await this.$api.postInfo
          .uploadNewfile(data)
          .then((res) => {
            console.log(res);
            this.$message.success(data.path+'上传成功！')
        }).catch((err) => {
          if(data.path.indexOf('-th/') != -1) {
            this.$message.warning(data.path+'已存在或上传失败！')
          }
        });
    },
    async afterUp() {
      let myDiv = document.getElementById('upDiv')
      myDiv.innerHTML = ''
      this.fileList = []
      this.queryArr = []
      setTimeout(()=>{
        this.loading = false
      }, 1200)
    },
    async getPer(i, queryLen) {
      this.percentage = Number(((i+1)/queryLen*100).toFixed(0));
      console.log(this.percentage, '//');
    },
    async dealPic() {
      let queryLen = this.queryArr.length
        if(queryLen>0) {
          this.loading = true
          for(let i=0; i< this.queryArr.length; ++i){
            await this.upload(this.queryArr[i][0]);
            await this.upload(this.queryArr[i][1]);
            await this.getPer(i, queryLen);
          }
        } else {
					this.$message.warning('无文件')
        }
        await this.afterUp()
    },
    getBase64(file) {
        return new Promise(function (resolve, reject) {
            let reader = new FileReader();
            let imgResult = "";
            reader.onload = function () {
                imgResult = reader.result;
            };
            reader.onerror = function (error) {
                reject(error);
            };
            reader.onloadend = function () {
                resolve(imgResult);
            };
            reader.readAsDataURL(file);
        });
    },
    async getQueryArr(tmp) {
        if(tmp.length==0) {return;}
        for(let i=0; i<tmp.length; ++i) {
            await this.getBase64(tmp[i]).then(res => {
                console.log(i, res.slice(0, 40));
                let resData = res.split(";base64,")[1];
                let myDiv = document.getElementById('upDiv')
                let canv = document.createElement('canvas')
								canv.style.background = "#bbb"
                canv.setAttribute('width', '100')
                canv.setAttribute('height', '100')
                canv.setAttribute('key', tmp[i].name)
                myDiv.appendChild(canv)
                let ctx = canv.getContext('2d')
                let img = new Image()
                img.src = res;
                img.onload=()=> {
                    let point = 0
                    if(img.height>img.width) {
                        point = Number((Number(Math.floor(img.height/2)) - Number(Math.floor(img.width/2))).toFixed(0))
                        ctx.drawImage(img, 0, point, img.width, img.width, 0, 0, 100, 100);
                    } else if(img.height<img.width) {
                        point = Number((Number(Math.floor(img.width/2)) - Number(Math.floor(img.height/2))).toFixed(0))
                        ctx.drawImage(img, point, 0, img.height, img.height, 0, 0, 100, 100);
                    }
                    let dataUrl = canv.toDataURL()
                    let resData1 = dataUrl.split(";base64,")[1];
                    console.log(resData1.slice(0, 40));
                    console.log(resData.slice(0, 40));
                    let nowDate = this.$moment(new Date()).format("YYYYMMDD")
                    let dirName = this.dirName ? this.dirName.replace(" ", '') : '杂'
                    let upDir = `${dirName}/${nowDate}/${tmp[i].name}`
                    let upDir1 = `${dirName}-th/${nowDate}/${tmp[i].name}`
                    let upTime = this.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
                    this.queryArr.push([
                        {
                          ...this.data,
                          content: resData1,
                          path: upDir1,
                          message: `上传${upDir1}>${upTime}`
                        },
                        {
                          ...this.data,
                          content: resData,
                          path: upDir,
                          message: `上传${upDir}>${upTime}`
                        }
                    ])
                }
            })
        }
    },
  },
  created() {
    let userInfo = JSON.parse(localStorage.getItem('userInfo'))
    if(userInfo) {
        this.data['access_token'] = userInfo['access_token']
    }
  },
}
</script>
<style lang="scss">
.upload {
  .upload-div {
    .el-select {
      .el-input {
        input {
          border-radius: 50px !important;
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.upload {
  height: 100%;
  display: flex;
  flex-direction: column;
  .upload-div {
    display: flex;
    flex: 1;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    #upDiv {
      background-color: rgba($color: #777, $alpha: 0.1);
      display: flex;
      flex-flow: row wrap;
      justify-content: center;
    }
    .tip {
      display: flex;
      justify-content: center;
      font-size: 12px;
      color: #999;
    }
    .btn-area {
      width:100%;
      margin: 10px auto;
      display: flex;
      justify-content: center;
      .upload-area {
        position: relative;
        #file {
          position: absolute;
          overflow: hidden;
          right: 0;
          top: 0;
          opacity: 0;
        }
      }
    }
    .progress-area {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      span {
        font-size: 13px;
        color: #888;
      }
    }
  }
}
</style>